package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.StaffRepository;
import cn.hd01.repository.entity.Staff;
import cn.hd01.service.StaffService;

@Service
public class StaffServiceImpl extends BaseServiceImpl<Staff, Integer> implements StaffService {

	private StaffRepository repository;

	@Autowired
	public StaffServiceImpl(StaffRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	@Cacheable(value = "staff", key = "#p0")
	public Staff findByOauthId(Integer oauthId) {
		return repository.findByOauthId(oauthId);
	}

	@Override
	public Page<Staff> find(final Staff u, Pageable pageable) {
		if (u == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<Staff>() {
			@Override
			public Predicate toPredicate(Root<Staff> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();

				if (StringUtils.hasText(u.getName())) {
					predicates.add(cb.like(r.get("name").as(String.class), "%" + u.getName() + "%"));
				}

				if (StringUtils.hasText(u.getPhone())) {
					predicates.add(cb.like(r.get("phone").as(String.class), "%" + u.getPhone() + "%"));
				}

				if (StringUtils.hasText(u.getType())) {
					predicates.add(cb.equal(r.get("type").as(String.class), u.getType()));
				}

				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
	}

	@Override
	public List<Staff> findByType(String type) {
		return repository.findByType(type);
	}

	@Override
	public Staff findByNameAndPassword(String name, String password) {
		return repository.findByNameAndPassword(name, password);
	}

	@Override
	public boolean exists(String phone) {
		return repository.countByPhone(phone) > 0;
	}
}
